package com.easylinkin.linkappapi.deviceservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.easylinkin.linkappapi.common.exceptions.BusinessException;
import com.easylinkin.linkappapi.deviceattribute.entity.DeviceAttributeTenantConfig;
import com.easylinkin.linkappapi.deviceservice.entity.DeviceServiceTenantConfig;
import com.easylinkin.linkappapi.deviceservice.entity.DeviceServices;
import com.easylinkin.linkappapi.deviceservice.mapper.DeviceServiceTenantConfigMapper;
import com.easylinkin.linkappapi.deviceservice.service.DeviceServiceService;
import com.easylinkin.linkappapi.deviceservice.service.DeviceServiceTenantConfigService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import com.easylinkin.linkappapi.security.entity.LinkappUser;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

/**
 * <p>
 * 设备服务租户个性化配置 服务实现类
 * </p>
 *
 * @author TongJie
 * @since 2020-10-28
 */
@Service
public class DeviceServiceTenantConfigServiceImpl extends ServiceImpl<DeviceServiceTenantConfigMapper, DeviceServiceTenantConfig> implements DeviceServiceTenantConfigService {

    private static final Logger LOGGER = LoggerFactory.getLogger(DeviceServiceTenantConfigServiceImpl.class);

    @Resource
    private LinkappUserContextProducer linkappUserContextProducer;

    @Resource
    private DeviceServiceService deviceServiceService;

    @Override
    public void batchSaveDeviceServiceTenantConfigs(List<DeviceServiceTenantConfig> deviceServiceTenantConfigList) {
        Assert.notEmpty(deviceServiceTenantConfigList, "deviceServiceTenantConfigList 参数列表为空");

        int sortNo = 0;

        for (DeviceServiceTenantConfig deviceServiceTenantConfig : deviceServiceTenantConfigList) {
            deviceServiceTenantConfig.setSortNo(sortNo++);
            add(deviceServiceTenantConfig);
        }
    }

    @Override
    public void add(DeviceServiceTenantConfig deviceServiceTenantConfig) {
        validParamRequired(deviceServiceTenantConfig);
        validParamFormat(deviceServiceTenantConfig);
        validRepeat(deviceServiceTenantConfig);
        if (StringUtils.isEmpty(deviceServiceTenantConfig.getTenantId())) {
            LinkappUser user = linkappUserContextProducer.getCurrent();
            deviceServiceTenantConfig.setTenantId(user.getTenantId());
        }
        saveOrUpdate(deviceServiceTenantConfig);
    }

    private void validRepeat(DeviceServiceTenantConfig deviceServiceTenantConfig) {
//        服务id + 租户id 不能重复
        QueryWrapper<DeviceServiceTenantConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("device_service_id", deviceServiceTenantConfig.getDeviceServiceId());
        queryWrapper.eq("tenant_id", deviceServiceTenantConfig.getTenantId());
        List<DeviceServiceTenantConfig> list = baseMapper.selectList(queryWrapper);
        if (list.size() == 0) {
            return;
        }
        if (list.size() > 1) {
            throw new BusinessException("同租户下已存在相同的服务配置");
        }
        if (StringUtils.isEmpty(deviceServiceTenantConfig.getId())) {
            throw new BusinessException("同租户下已存在相同的服务配置");
        }
        if (!deviceServiceTenantConfig.getId().equals(list.get(0).getId())) {
            throw new BusinessException("同租户下已存在相同的服务配置");
        }
        
    }


    /**
     * 校验参数必填
     */
    private void validParamRequired(DeviceServiceTenantConfig deviceServiceTenantConfig) {
        Assert.notNull(deviceServiceTenantConfig, "参数为空");
        Assert.notNull(deviceServiceTenantConfig.getSortNo(), "参数'序号' 为空");
        Assert.notNull(deviceServiceTenantConfig.getIsShow(), "参数'是否显示' 为空");
        Assert.isTrue(StringUtils.isNotBlank(deviceServiceTenantConfig.getTenantId()), "租户id为空");
        Assert.isTrue(StringUtils.isNotBlank(deviceServiceTenantConfig.getDeviceServiceId()), "服务id 为空");
    }

    /**
     * 校验参数格式
     */
    private void validParamFormat(DeviceServiceTenantConfig deviceServiceTenantConfig) {
        Assert.isTrue(deviceServiceTenantConfig.getDeviceServiceId() == null || deviceServiceTenantConfig.getDeviceServiceId().length() <= 32, "参数 deviceServiceId 超长");
        Assert.isTrue(deviceServiceTenantConfig.getTenantId() == null || deviceServiceTenantConfig.getTenantId().length() <= 32, "租户id超长");
    }

    @Override
    public List<DeviceServiceTenantConfig> getDeviceServiceTenantConfigs(DeviceServiceTenantConfig deviceServiceTenantConfig) {
        if (StringUtils.isEmpty(deviceServiceTenantConfig.getTenantId())) {
            deviceServiceTenantConfig.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        }
        return baseMapper.getDeviceServiceTenantConfigs(deviceServiceTenantConfig);
    }

//    @Override
//    public void inheritPersonalizedConfig(Set<String> addDeviceServicesIds) {
//        if (ObjectUtils.isEmpty(addDeviceServicesIds)) {
//            return;
//        }
//        List<DeviceServiceTenantConfig> deviceServiceTenantConfigs = baseMapper.getLatestToBeUpdatedPersonalizedConfig(addDeviceServicesIds);
//
//        for (DeviceServiceTenantConfig deviceServiceTenantConfig : deviceServiceTenantConfigs) {
//            if (deviceServiceTenantConfig.getIsShow() == null) {
//                deviceServiceTenantConfig.setIsShow(false);
//            }
//            if (deviceServiceTenantConfig.getSortNo() == null) {
//                deviceServiceTenantConfig.setSortNo(0);
//            }
//            updateById(deviceServiceTenantConfig);
//        }
////  当同时用到了 高版本和低版本对应的 服务id 删除与低版本的关联 只保留高的
//        baseMapper.deleteServiceIdentifierRepeatData();
//
//        //  如果 linkthings有新增的属性 需要插入到个性化配置中，默认设置为不可见
//        List<DeviceServiceTenantConfig> deviceServiceTenantConfigList = baseMapper.getNeedAddConfigAfterInheritPersonalizedConfig();
//        for (DeviceServiceTenantConfig deviceServiceTenantConfig : deviceServiceTenantConfigList) {
//            deviceServiceTenantConfig.setSortNo(0);
//            deviceServiceTenantConfig.setIsShow(false);
//            save(deviceServiceTenantConfig);
//        }
//    }

    @Override
    public void inheritPersonalizedConfig(String existRefUnitId, String tenantId, String newDeviceUnitId) {
        deleteByTenantIdAndUnitId(tenantId,existRefUnitId);
        deleteByTenantIdAndUnitId(tenantId,newDeviceUnitId);
        //新增新的服务
        DeviceServices param = new DeviceServices();
        param.setDeviceUnitId(newDeviceUnitId);
        List<DeviceServices> newDeviceServiceList = deviceServiceService.getDeviceServicesList(param);
        if(!CollectionUtils.isEmpty(newDeviceServiceList)){
            for (DeviceServices deviceServices : newDeviceServiceList) {
                DeviceServiceTenantConfig deviceServiceTenantConfig = new DeviceServiceTenantConfig();
                deviceServiceTenantConfig.setTenantId(tenantId);
                deviceServiceTenantConfig.setDeviceServiceId(deviceServices.getId());
                deviceServiceTenantConfig.setIsShow(deviceServices.getIsShow());
                deviceServiceTenantConfig.setSortNo(deviceServices.getSortNo());
                save(deviceServiceTenantConfig);
            }
        }

    }

    @Override
    public void deleteByTenantIdAndUnitId(String tenantId, String existRefUnitId) {
        //删除以前的配置
        DeviceServices existService = new DeviceServices();
        existService.setDeviceUnitId(existRefUnitId);
        List<DeviceServices> deviceServicesList = deviceServiceService.getDeviceServicesList(existService);
        if(!CollectionUtils.isEmpty(deviceServicesList)){
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("tenant_id",tenantId);
            queryWrapper.in("device_service_id",deviceServicesList.stream().map(DeviceServices::getId).collect(Collectors.toList()));
            baseMapper.delete(queryWrapper);
        }
    }

}
